package com.basic.modules.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.exception.RRException;
import com.basic.common.utils.*;
import com.basic.modules.sys.dao.SysUserDao;
import com.basic.modules.sys.entity.SysRoleEntity;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.entity.SysUserRoleEntity;
import com.basic.modules.sys.model.CurSerExcel;
import com.basic.modules.sys.model.EmployeeManagementExcel;
import com.basic.modules.sys.service.SysRoleService;
import com.basic.modules.sys.service.SysUserRoleService;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.entity.YkfCustomerShopEntity;
import com.basic.modules.ykf.entity.YkfCustomerSubAccountEntity;
import com.basic.modules.ykf.model.CommissionModel;
import com.basic.modules.ykf.model.ExcelReq;
import com.basic.modules.ykf.service.YkfAccountInputRecordService;
import com.basic.modules.ykf.service.YkfCustomerShopService;
import com.basic.modules.ykf.service.YkfCustomerSubAccountService;
import com.basic.modules.ykf.utils.ExcelCellWidthStyleStrategy;
import com.basic.modules.ykf.utils.ExcelStyleUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;
    @Lazy
    @Autowired
    private YkfCustomerSubAccountService subAccountService;

    @Lazy
    @Autowired
    private YkfCustomerShopService ykfCustomerShopService;

    @Lazy
    @Autowired
    private YkfAccountInputRecordService inputRecordService;

    @Override
    public PageUtils queryPage(ParamsModel<SysUserEntity> params) {
        QueryWrapper<SysUserEntity> queryWrapper = ParamUtils.createQueryWrapperBySort(params);
        if (ObjectUtil.isNotEmpty(params.getCondition().getKeyword())) {
            String keyword = params.getCondition().getKeyword();
            queryWrapper.lambda().and(wrapper -> wrapper.like(SysUserEntity::getName, keyword)
                    .or().like(SysUserEntity::getFlowerName, keyword)
                    .or().like(SysUserEntity::getUserId, keyword)
                    .or().like(SysUserEntity::getNo, keyword)
                    .or().like(SysUserEntity::getMobile, keyword));
        }
        List<String> companyNos = this.getPowerCompanyNos();
        if (ObjectUtil.isNotEmpty(companyNos)) {
            if (!companyNos.contains("ALL")) {
                queryWrapper.lambda().in(SysUserEntity::getCompanyNo, companyNos);
            }
        } else {
            return new PageUtils();
        }
        IPage<SysUserEntity> queryPage = new Query<SysUserEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        IPage<SysUserEntity> page = this.page(
                queryPage, queryWrapper
        );
//        if (ObjectUtil.isNotEmpty(page) && ObjectUtil.isNotEmpty(page.getRecords())) {
//            for (SysUserEntity item : page.getRecords()) {
//                //查询同类笔数
//                //查询正在服务店铺数
//                //查询当月提成
//            }
//        }
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryCusSerPage(ParamsModel<SysUserEntity> params) {
        Long shopId = params.getCondition().getShopId();
        QueryWrapper<SysUserEntity> queryWrapper = ParamUtils.createQueryWrapperBySort(params);
        if (ObjectUtil.isNotEmpty(params.getCondition().getKeyword())) {
            String keyword = params.getCondition().getKeyword();
            queryWrapper.lambda().and(wrapper -> wrapper.like(SysUserEntity::getName, keyword)
                    .or().like(SysUserEntity::getFlowerName, keyword)
                    .or().like(SysUserEntity::getUserId, keyword)
                    .or().like(SysUserEntity::getNo, keyword)
                    .or().like(SysUserEntity::getMobile, keyword));
        }
        if (StrUtil.isNotBlank(params.getCondition().getCompanyNo())) {
            queryWrapper.lambda().eq(SysUserEntity::getCompanyNo, params.getCondition().getCompanyNo());
        }
        List<String> postNos = new ArrayList<>();
        postNos.add("客服");
        postNos.add("客服部经理");
        postNos.add("客服部副经理");
        postNos.add("客服部主管");
        queryWrapper.lambda().in(SysUserEntity::getPostNo, postNos);

        List<Long> powerUIds = this.getPowerUIds();
        if (ObjectUtil.isEmpty(powerUIds)) {
            return new PageUtils();
        } else {
            if (!powerUIds.contains(0L)) {
                queryWrapper.lambda().in(SysUserEntity::getUserId, powerUIds);
            }
        }
        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(BeanUtil.beanToMap(params.getPage())),
                queryWrapper
        );
        if (ObjectUtil.isNotEmpty(page) && ObjectUtil.isNotEmpty(page.getRecords())) {
            //查询当前店铺类别
            String shopTypeNo = "";
            YkfCustomerShopEntity shop = ykfCustomerShopService.getById(shopId);
            if (ObjectUtil.isNotEmpty(shop)) {
                shopTypeNo = shop.getShopTypeNo();
            }
            DateTime date = DateUtil.date();
            for (SysUserEntity record : page.getRecords()) {
                record.setShopTypeCount("同类" + 0);
                record.setServerShopCount("正在服务" + 0);
                record.setCommissionSalary("当月提成" + 0);
                //查询正在服务的店铺
                if (StrUtil.isNotBlank(shopTypeNo)) {
                    int count = baseMapper.getShopTypeCount(record.getUserId(), shopTypeNo);
                    record.setShopTypeCount("同类" + count);
                }
                //查询正在服务店铺数
                int count = baseMapper.getServerShopCount(record.getUserId(), date);
                record.setServerShopCount("正在服务" + count);
                //查询当月提成
                CommissionModel commissionModel = inputRecordService.commissionCheckPage(record.getUserId());
                if (ObjectUtil.isNotEmpty(commissionModel) && ObjectUtil.isNotEmpty(commissionModel.getCommissionSalary())) {
                    record.setCommissionSalary("当月提成" + commissionModel.getCommissionSalary().toString());
                }
            }
        }
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void dispatchRole(SysUserEntity user) {
        QueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
        sysUserRoleService.remove(queryWrapper);
        if (ObjectUtil.isNotEmpty(user.getRoleIdList())) {
            List<SysUserRoleEntity> list = new ArrayList<>();
            for (Long roleId : user.getRoleIdList()) {
                SysUserRoleEntity userRole = new SysUserRoleEntity();
                userRole.setRoleId(roleId);
                userRole.setUserId(user.getUserId());
                list.add(userRole);
            }
            sysUserRoleService.saveBatch(list);
        }
    }

    @Override
    public List<SysRoleEntity> searchDispatchRole(SysUserEntity user) {
        QueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
        List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper);
        if (ObjectUtil.isNotEmpty(list)) {
            List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
            return sysRoleService.listByIds(roleIds);
        }
        return new ArrayList<>();
    }

    @Override
    public void employeeManagement(ExcelReq req, HttpServletResponse response) throws IOException {
        List<EmployeeManagementExcel> list = new ArrayList<>();
        //查询列表
        ParamsModel<SysUserEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<SysUserEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = queryPage(params);
        List<SysUserEntity> dataList = (List<SysUserEntity>) pageUtils.getList();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (SysUserEntity record : dataList) {
                EmployeeManagementExcel excel = new EmployeeManagementExcel();
                BeanUtil.copyProperties(record, excel);
                if (null == record.getBecomeRegularStatus()) {
                    record.setBecomeRegularStatus(1);
                }
                if (null == record.getOnDutyStatus()) {
                    record.setOnDutyStatus(1);
                }
                excel.setBecomeRegularStatus(record.getBecomeRegularStatus() == 0 ? "试用期" : "已转正");
                excel.setOnDutyStatus(record.getOnDutyStatus() == 0 ? "离职" : "在职");
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("员工信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), EmployeeManagementExcel.class)
                .sheet("员工信息")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    @Override
    public List<Long> getPowerUserIds() {
        SysUserEntity user = CommonUtils.getUser();
        if (StrUtil.equals(user.getUsername(), "admin")) {
            return new ArrayList<>();
        }
        Long userId = user.getUserId();
        List<Long> userIds = new ArrayList<>();
        //查询角色
        QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, userId);
        List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
        if (ObjectUtil.isNotEmpty(list)) {
            List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
            List<SysRoleEntity> sysRoleList = sysRoleService.listByIds(roleIds);
            if (ObjectUtil.isNotEmpty(sysRoleList)) {
                List<String> dataPerms = sysRoleList.stream().map(SysRoleEntity::getDataPerms).distinct().collect(Collectors.toList());
                //过滤城市权限
                List<String> companyPerms = sysRoleList.stream().map(SysRoleEntity::getCompanyPerms).distinct().collect(Collectors.toList());
                QueryWrapper<SysUserEntity> queryWrapper2 = new QueryWrapper<>();
                if (dataPerms.contains("3")) {
                    if (!companyPerms.contains("ALL")) {
                        queryWrapper2.lambda().in(SysUserEntity::getCompanyNo, companyPerms);
                    }
                    List<SysUserEntity> userList = this.list(queryWrapper2);
                    if (ObjectUtil.isNotEmpty(userList)) {
                        return userList.stream().map(SysUserEntity::getUserId).distinct().collect(Collectors.toList());
                    } else {
                        userIds.add(userId);
                        return userIds;
                    }
                } else if (dataPerms.contains("2")) {
                    //查询部门下所有用户
                    String deptNo = user.getDeptNo();
                    queryWrapper2.lambda().eq(SysUserEntity::getDeptNo, deptNo);
                    if (!companyPerms.contains("ALL")) {
                        queryWrapper2.lambda().in(SysUserEntity::getCompanyNo, companyPerms);
                    }
                    List<SysUserEntity> userList = this.list(queryWrapper2);
                    if (ObjectUtil.isNotEmpty(userList)) {
                        return userList.stream().map(SysUserEntity::getUserId).distinct().collect(Collectors.toList());
                    } else {
                        userIds.add(userId);
                        return userIds;
                    }
                } else if (dataPerms.contains("1")) {
                    userIds.add(userId);
                    return userIds;
                }

            } else {
                userIds.add(userId);
                return userIds;
            }
        }
        userIds.add(userId);
        return userIds;
    }

    /**
     * 返回属于这个人所属公司的所有子账号id
     *
     * @return
     */
    @Override
    public List<Long> getPowerSubAccountIds() {
        SysUserEntity user = CommonUtils.getUser();
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
            List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                List<SysRoleEntity> roleList = sysRoleService.listByIds(roleIds);
                if (ObjectUtil.isNotEmpty(roleList)) {
                    List<String> collect = roleList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                    if (!collect.contains("ALL")) {
                        QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().in(YkfCustomerSubAccountEntity::getCompanyNo, collect);
                        List<YkfCustomerSubAccountEntity> list1 = subAccountService.list(queryWrapper);
                        if (ObjectUtil.isNotEmpty(list1)) {
                            return list1.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
                        }
                    } else {
                        return Collections.singletonList(0L);
                    }
                }
            }
        } else {
            return Collections.singletonList(0L);
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> getOneselfPowerSubAccountIds() {
        SysUserEntity user = CommonUtils.getUser();
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            if (getOneselfFlag(user.getUserId())) {
                List<Long> oneselfShopIds = getShopIdsByUserId(user.getUserId());
                if (ObjectUtil.isEmpty(oneselfShopIds)) {
                    return new ArrayList<>();
                } else {
                    //查询店铺下所有子账号
                    QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().in(YkfCustomerSubAccountEntity::getShopId, oneselfShopIds);
                    List<YkfCustomerSubAccountEntity> list = subAccountService.list(queryWrapper);
                    if (ObjectUtil.isNotEmpty(list)) {
                        return list.stream().map(YkfCustomerSubAccountEntity::getSubAccountId).distinct().collect(Collectors.toList());
                    }
                }
            } else {
                return getPowerSubAccountIds();
            }
        } else {
            return Collections.singletonList(0L);
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> getPowerCustomerShopIds() {
        // 返回属于这个人所属公司的所有子账号id
        List<Long> powerSubAccountIds = getPowerSubAccountIds();
        if (ObjectUtil.isNotEmpty(powerSubAccountIds)) {
            if (powerSubAccountIds.contains(0L)) {
                // 是管理员直接返回0
                return Collections.singletonList(0L);
            } else {
                // 根据子账号ID查询出所有子账号数据
                List<YkfCustomerSubAccountEntity> list = subAccountService.listByIds(powerSubAccountIds);
                if (ObjectUtil.isNotEmpty(list)) {
                    // 又根据子账号数据找出所有店铺ID并进行去重
                    return list.stream().map(YkfCustomerSubAccountEntity::getShopId).distinct().collect(Collectors.toList());
                }
            }
        }
        return new ArrayList<>();
    }


    @Override
    public List<Long> getOneselfPowerCustomerShopIds() {
        SysUserEntity user = CommonUtils.getUser();
        // 是不是管理员？
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            // 返回false意味着这个用户属于某个公司的管理员
            if (getOneselfFlag(user.getUserId())) {
                // 不是管理员,根据店铺表的create_user_id只查这个用户自己创建的店铺
                List<Long> oneselfShopIds = getShopIdsByUserId(user.getUserId());
                if (ObjectUtil.isEmpty(oneselfShopIds)) {
                    return new ArrayList<>();
                } else {
                    return oneselfShopIds;
                }
            } else {
                // 如果属于某个公司的管理员,找到这个所属这个公司的店铺ID集合
                return getPowerCustomerShopIds();
            }
        } else {
            // 是管理员,直接给0
            return Collections.singletonList(0L);
        }
    }


    @Override
    public List<Long> getPowerCustomerShopIds(List<Long> powerSubAccountIds) {
        if (ObjectUtil.isNotEmpty(powerSubAccountIds)) {
            if (powerSubAccountIds.contains(0L)) {
                return Collections.singletonList(0L);
            } else {
                //查询
                List<YkfCustomerSubAccountEntity> list = subAccountService.listByIds(powerSubAccountIds);
                if (ObjectUtil.isNotEmpty(list)) {
                    return list.stream().map(YkfCustomerSubAccountEntity::getShopId).distinct().collect(Collectors.toList());
                }
            }
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> getPowerCustomerIds() {
        List<Long> powerSubAccountIds = getPowerSubAccountIds();
        if (ObjectUtil.isNotEmpty(powerSubAccountIds)) {
            if (powerSubAccountIds.contains(0L)) {
                return Collections.singletonList(0L);
            } else {
                //查询
                List<YkfCustomerSubAccountEntity> list = subAccountService.listByIds(powerSubAccountIds);
                if (ObjectUtil.isNotEmpty(list)) {
                    return list.stream().map(YkfCustomerSubAccountEntity::getCustomerId).distinct().collect(Collectors.toList());
                }
            }
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> getPowerUIds() {
        SysUserEntity user = CommonUtils.getUser();
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
            List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                List<SysRoleEntity> roleList = sysRoleService.listByIds(roleIds);
                if (ObjectUtil.isNotEmpty(roleList)) {
                    List<String> collect = roleList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                    if (!collect.contains("ALL")) {
                        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().in(SysUserEntity::getCompanyNo, collect);
                        List<SysUserEntity> list1 = this.list(queryWrapper);
                        if (ObjectUtil.isNotEmpty(list1)) {
                            return list1.stream().map(SysUserEntity::getUserId).distinct().collect(Collectors.toList());
                        }
                    } else {
                        return Collections.singletonList(0L);
                    }
                }
            }
        } else {
            return Collections.singletonList(0L);
        }
        return new ArrayList<>();
    }


    @Override
    public boolean isMasterCompany() {
        SysUserEntity user = CommonUtils.getUser();
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
            List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                List<SysRoleEntity> roleList = sysRoleService.listByIds(roleIds);
                if (ObjectUtil.isNotEmpty(roleList)) {
                    List<String> collect = roleList.stream().map(SysRoleEntity::getCompanyPerms).collect(Collectors.toList());
                    if (!collect.contains("ALL")) {
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        } else {
            return true;
        }
        return false;
    }

    @Override
    public List<String> getPowerCompanyNos() {
        SysUserEntity user = CommonUtils.getUser();
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, user.getUserId());
            List<SysUserRoleEntity> list = sysUserRoleService.list(queryWrapper1);
            if (ObjectUtil.isNotEmpty(list)) {
                List<Long> roleIds = list.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
                List<SysRoleEntity> roleList = sysRoleService.listByIds(roleIds);
                if (ObjectUtil.isNotEmpty(roleList)) {
                    return roleList.stream().map(SysRoleEntity::getCompanyPerms).distinct().collect(Collectors.toList());
                }
            }
        } else {
            return Collections.singletonList("ALL");
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> getPowerCustomerIds(List<Long> powerSubAccountIds) {
        if (ObjectUtil.isNotEmpty(powerSubAccountIds)) {
            if (powerSubAccountIds.contains(0L)) {
                return Collections.singletonList(0L);
            } else {
                //查询
                List<YkfCustomerSubAccountEntity> list = subAccountService.listByIds(powerSubAccountIds);
                if (ObjectUtil.isNotEmpty(list)) {
                    return list.stream().map(YkfCustomerSubAccountEntity::getCustomerId).distinct().collect(Collectors.toList());
                }
            }
        }
        return new ArrayList<>();
    }


    @Override
    public List<Long> getOneselfShopIds() {
        Long userId = CommonUtils.getUserId();
        if (getOneselfFlag(userId)) {
            //查询创建人的店铺
            QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfCustomerShopEntity::getCreateUserId, userId);
            List<YkfCustomerShopEntity> list = ykfCustomerShopService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                return list.stream().map(YkfCustomerShopEntity::getShopId).distinct().collect(Collectors.toList());
            } else {
                return new ArrayList<>();
            }
        }
        return Collections.singletonList(0L);
    }

    public List<Long> getShopIdsByUserId(Long userId) {
        //查询创建人的店铺
        QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerShopEntity::getCreateUserId, userId);
        List<YkfCustomerShopEntity> list = ykfCustomerShopService.list(queryWrapper);
        if (ObjectUtil.isNotEmpty(list)) {
            return list.stream().map(YkfCustomerShopEntity::getShopId).distinct().collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 返回false意味着这个用户属于某个公司的管理员
     *
     * @param userId
     * @return
     */
    @Override
    public boolean getOneselfFlag(Long userId) {
        if (userId == Constant.SUPER_ADMIN) {
            return false;
        }
        QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, userId);
        // 找到该员工的角色列表
        List<SysUserRoleEntity> userRoleList = sysUserRoleService.list(queryWrapper1);
        if (ObjectUtil.isNotEmpty(userRoleList)) {
            List<Long> roleIds = userRoleList.stream().map(SysUserRoleEntity::getRoleId).distinct().collect(Collectors.toList());
            QueryWrapper<SysRoleEntity> queryWrapper2 = new QueryWrapper<>();
            // dataPerms是3为某公司管理员,1为某公司普通员工
            queryWrapper2.lambda().in(SysRoleEntity::getRoleId, roleIds)
                    .eq(SysRoleEntity::getDataPerms, "1");
            if (sysRoleService.count(queryWrapper2) > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean getOneselfFlag() {
        Long userId = CommonUtils.getUserId();
        if (userId == Constant.SUPER_ADMIN) {
            return false;
        }
        QueryWrapper<SysUserRoleEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(SysUserRoleEntity::getUserId, userId);
        List<SysUserRoleEntity> userRoleList = sysUserRoleService.list(queryWrapper1);
        if (ObjectUtil.isNotEmpty(userRoleList)) {
            List<Long> roleIds = userRoleList.stream().map(SysUserRoleEntity::getRoleId).distinct().collect(Collectors.toList());
            QueryWrapper<SysRoleEntity> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().in(SysRoleEntity::getRoleId, roleIds)
                    .eq(SysRoleEntity::getDataPerms, "1");
            int count = sysRoleService.count(queryWrapper2);
            if (count > 0 && count == roleIds.size()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    @Transactional
    public void saveUser(SysUserEntity user) {
        validUser(user);
        user.setCreateTime(new Date());
        //sha256加密
        if (StrUtil.isNotBlank(user.getPassword())) {
            String salt = RandomStringUtils.randomAlphanumeric(20);
            user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
            user.setSalt(salt);
        }
        this.save(user);

//		//检查角色是否越权
//		checkRole(user);
//
//		//保存用户与角色关系
//		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(SysUserEntity user) {
        validUser(user);
//		if(StringUtils.isBlank(user.getPassword())){
//			user.setPassword(null);
//		}else{
//			SysUserEntity oldUser = this.getById(user);
//			user.setPassword(new Sha256Hash(user.getPassword(), oldUser.getSalt()).toHex());
//		}
        SysUserEntity old = this.getById(user.getUserId());
        if (StrUtil.isNotBlank(old.getCompanyNo()) && !StrUtil.equals(old.getCompanyNo(), user.getCompanyNo())) {
            //公司不一样须交验是否存在未停用的子账号
            QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper = new QueryWrapper<>();
            DateTime date = DateUtil.date();
            queryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getUserId, user.getUserId())
                    .le(YkfCustomerSubAccountEntity::getStartDate, date)
                    .ge(YkfCustomerSubAccountEntity::getEndDate, date)
                    .eq(YkfCustomerSubAccountEntity::getStatus, 1);
            if (subAccountService.count(queryWrapper) > 0) {
                throw new RRException("有子账号正在服务，暂不支持修改公司，请先停用子账号，再操作");
            }
        }
        if (ObjectUtil.isNotEmpty(old.getOnDutyStatus()) && old.getOnDutyStatus() == 1 && user.getOnDutyStatus() == 0) {
            DateTime date = DateUtil.date();
            //离职须交验是否存在未停用的子账号
            QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getUserId, user.getUserId())
                    .le(YkfCustomerSubAccountEntity::getStartDate, date)
                    .ge(YkfCustomerSubAccountEntity::getEndDate, date)
                    .eq(YkfCustomerSubAccountEntity::getStatus, 1);
            if (subAccountService.count(queryWrapper) > 0) {
                throw new RRException("有子账号正在服务，暂不可以操作离职，请先停用子账号，再操作");
            }
        }
        this.updateById(user);

//		//检查角色是否越权
//		checkRole(user);
//
//		//保存用户与角色关系
//		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(Long userId, String password, String salt) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(password);
        userEntity.setSalt(salt);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId));
    }

    /**
     * 校验重复
     */
    private void validUser(SysUserEntity user) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserEntity::getMobile, user.getMobile());
        if (ObjectUtil.isNotEmpty(user.getUserId())) {
            queryWrapper.lambda().ne(SysUserEntity::getUserId, user.getUserId());
        }
        if (this.count(queryWrapper) > 0) {
            throw new RRException("手机号已存在,请检查");
        }
        QueryWrapper<SysUserEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(SysUserEntity::getNo, user.getNo());
        if (ObjectUtil.isNotEmpty(user.getUserId())) {
            queryWrapper1.lambda().ne(SysUserEntity::getUserId, user.getUserId());
        }
        if (this.count(queryWrapper1) > 0) {
            throw new RRException("工号已存在,请检查");
        }
        QueryWrapper<SysUserEntity> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(SysUserEntity::getFlowerName, user.getFlowerName());
        if (ObjectUtil.isNotEmpty(user.getUserId())) {
            queryWrapper2.lambda().ne(SysUserEntity::getUserId, user.getUserId());
        }
        if (this.count(queryWrapper2) > 0) {
            throw new RRException("花名已存在,请检查");
        }
        user.setUsername(user.getMobile());
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
            return;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

        //判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new RRException("新增用户所选角色，不是本人创建");
        }
    }

    @Override
    public void customerServiceList(ExcelReq req, HttpServletResponse response) throws IOException {
        List<CurSerExcel> list = new ArrayList<>();
        //查询列表
        ParamsModel<SysUserEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<SysUserEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = queryCusSerPage(params);
        List<SysUserEntity> dataList = (List<SysUserEntity>) pageUtils.getList();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (SysUserEntity record : dataList) {
                CurSerExcel excel = new CurSerExcel();
                BeanUtil.copyProperties(record, excel);
                if (null == record.getBecomeRegularStatus()) {
                    record.setBecomeRegularStatus(1);
                }
                if (null == record.getOnDutyStatus()) {
                    record.setOnDutyStatus(1);
                }
                excel.setBecomeRegularStatus(record.getBecomeRegularStatus() == 0 ? "试用期" : "已转正");
                excel.setOnDutyStatus(record.getOnDutyStatus() == 0 ? "离职" : "在职");
                list.add(excel);
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客服信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), CurSerExcel.class)
                .sheet("客服信息")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
                .doWrite(list);
    }

    @Override
    public List<SysUserEntity> getKueFuList(String companyName, String postName) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>().eq("company_name", companyName).eq("pest_name", postName);
        return list(queryWrapper);
    }
}
